package com.huicoo.forestmanager.widget;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;


import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.others.Constants;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.SharedPreferenceUtil;
import com.huicoo.forestmanager.util.toast.ToastUtils;

import java.util.HashMap;

/**
 * 服务器根地址设置对话框
 */
public class BaseUrlSettingDialog extends AlertDialog {
    private OnSetBaseUrlListener onSetBaseUrlListener;

    public BaseUrlSettingDialog(Context context) {
        super(context, R.style.transDialog);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_base_url_setting);
        setCancelable(true);
        setCanceledOnTouchOutside(true);


    }

    public void showDialog(HashMap<String, String> urlMap) {
        if (urlMap == null || urlMap.isEmpty()) {
            ToastUtils.show("暂无配置信息");
            return;
        }

        show();

        EditText et_key = findViewById(R.id.et_key);
        String key = SharedPreferenceUtil.LoadStringData(Constants.PROJECT_NAME, Constants.BASE_URL_KEY);
        if (!TextUtils.isEmpty(key)) {
            et_key.setText(key);
        }

        findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = et_key.getText().toString().trim();
                if (TextUtils.isEmpty(key)) {
                    ToastUtils.show("请输入通道号");
                    return;
                }
                String baseUrl = urlMap.get(key);
                LogUtils.v("gogogo get key value = " + key + "  --  " + baseUrl);
                if (TextUtils.isEmpty(baseUrl)) {
                    ToastUtils.show("输入的通道号有误，请重试");
                    return;
                }
                if (onSetBaseUrlListener != null) {
                    onSetBaseUrlListener.confirm(key, baseUrl);
                }
            }
        });

        Window win = getWindow();
        if (win != null) {
            win.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        }
    }

    public interface OnSetBaseUrlListener {
        void confirm(String key, String baseUrl);
    }

    public void setOnSetBaseUrlListener(OnSetBaseUrlListener onSetBaseUrlListener) {
        this.onSetBaseUrlListener = onSetBaseUrlListener;
    }
}
